<?php

namespace gtf;

class Router {

  private static $config;

  protected static function split_($str) {
    $method = '';
    for ($i=1; $i<strlen($str) && $str[$i] != '/'; $i++) {
      $method .= $str[$i];
    }
    $str = substr($str, $i+1);
    return array("$method", $str);
  }

  public static function bootstrap($cls) {
    // obtain the request uri.
    if (! isset($_SERVER['PATH_INFO'])) {
      $uri = '/index';
    } else {
      $uri = $_SERVER['PATH_INFO']; 
    }

    list($method, $uri) = static::split_($uri);

    $cls->$method($uri);

  }

  private static function config($key=null) {
    if (static::$config == null) {
      $config = dirname(dirname(__FILE__)).'/site.config.php';
      static::$config = require $config;
    }

    if (isset($key)) {
      $key = explode('/', trim($key, '/'));
      $cur = static::$config;
      while ($k=array_shift($key)) {
        $cur = $cur[$k];
      }
      return $cur;
    } else {
      return static::$config;
    }
  }

  public static function res($path) {
    $baseUri = Router::config('baseUri');
    return "$baseUri/$path";
  }

}

